package com.example.comiccenter.service.implt;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.comiccenter.dao.ComicMapper;
import com.example.comiccenter.dao.LikeMapper;
import com.example.comiccenter.domain.Comic;
import com.example.comiccenter.domain.Likes;
import com.example.comiccenter.service.LikeService;
import com.example.comiccenter.utils.ResultData;
import com.example.comiccenter.utils.SearchBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LikeServiceImpl implements LikeService {

    @Resource
    private LikeMapper likeMapper;
    @Resource
    private ComicMapper comicMapper;

    @Override
    public ResultData getAllLike(SearchBean<Likes> searchBean) {
        QueryWrapper<Likes> wrapper = new QueryWrapper<>();
        wrapper.eq(searchBean.getData().getUsername()!=null,"username",searchBean.getData().getUsername())
                .eq(searchBean.getData().getComicId()!=null,"comicId",searchBean.getData().getComicId());
        Page<Likes> likesPage = likeMapper.selectPage(new Page<>(searchBean.getPageNum(), searchBean.getPageSize()), wrapper);
        return ResultData.success("查询成功",likesPage);
    }

    @Override
    public ResultData addLike(Likes like) {
        //先查询是否已经点赞
        QueryWrapper<Likes> wrapper = new QueryWrapper<>();
        wrapper.eq("username",like.getUsername())
                .eq("comicId",like.getComicId());
        if (likeMapper.selectCount(wrapper)>0) {
            return ResultData.error(400,"您已经点赞过了");
        }else{
            likeMapper.insert(like);
        }
        //comic点赞数量＋1
        //添加收藏完后修改comic的收藏数量
        QueryWrapper<Comic> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("id",like.getComicId());
        Comic comic = comicMapper.selectOne(wrapper1);
        comic.setLikes(comic.getCollects()+1);
        comic.setHeat(comic.getHeat()+1);

        comicMapper.updateById(comic);
        //
        return ResultData.success("点赞成功");
    }

    @Override
    public ResultData deleteLike(Likes like) {
        QueryWrapper<Likes> wrapper = new QueryWrapper<>();
        wrapper.eq("username",like.getUsername())
                .eq("comicId",like.getComicId());
        if (likeMapper.selectCount(wrapper)>0) {
            likeMapper.delete(wrapper);
            //添加收藏完后修改comic的收藏数量
            QueryWrapper<Comic> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id",like.getComicId());
            Comic comic = comicMapper.selectOne(wrapper1);
            comic.setLikes(comic.getCollects()-1);
            comic.setHeat(comic.getHeat()-1);
            comicMapper.updateById(comic);
            return ResultData.success("取消成功");
        }else {
            return ResultData.error(400,"您未点赞");
        }

    }
}
